<!DOCTYPE html>
<html lang="zh-cn"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/main.css" rel="stylesheet">

    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.ico" />

    <title>Go程序的for Range结构 | wiseAI的小站</title>
</head><body><div class="container-fluid">
    <nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">
                <img src="/img/favicon.ico" alt="" width="30" height="24" class="d-inline-block align-text-top">
                wiseAI的小站
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/articles/">文章</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/categories/">分类</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/tags/">关键字</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/post/golang/">golang编程</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/about/">关于</a>
                    </li>
                    
                </ul>
                <form class="d-flex">
                    <input id="search-query" class="form-control me-2" type="search" placeholder="Search for anything..." aria-label="Search">
                </form>
            </div>
        </div>
    </nav>
</div>




<div id="content">
<div class="container article">
	<h1>Go程序的for Range结构</h1>
	<div class="post-meta">
		<div>
			
			
			By wiseai | 2022-07-28 | 2 minutes
		</div>
		<div class="tags">
			
			<a class="btn btn-light links btn-sm" href="/tags/%E7%BC%96%E7%A8%8B/">编程</a>
			
		</div>
	</div>
	<div>
		<div class="article-post">
			<h1 id="73-for-range-结构">7.3 For-range 结构</h1>
<p>这种构建方法可以应用于数组和切片:</p>
<pre tabindex="0"><code>for ix, value := range slice1 {
	...
}
</code></pre><p>第一个返回值 <code>ix</code> 是数组或者切片的索引，第二个是在该索引位置的值；他们都是仅在 <code>for</code> 循环内部可见的局部变量。<code>value</code> 只是 <code>slice1</code> 某个索引位置的值的一个拷贝，不能用来修改 <code>slice1</code> 该索引位置的值。</p>
<p>示例 7.9 <a href="examples/chapter_7/slices_forrange.go">slices_forrange.go</a></p>
<pre tabindex="0"><code>package main

import &#34;fmt&#34;

func main() {
	var slice1 []int = make([]int, 4)

	slice1[0] = 1
	slice1[1] = 2
	slice1[2] = 3
	slice1[3] = 4

	for ix, value := range slice1 {
		fmt.Printf(&#34;Slice at %d is: %d\n&#34;, ix, value)
	}
}
</code></pre><p>示例 7.10 <a href="examples/chapter_7/slices_forrange2.go">slices_forrange2.go</a></p>
<pre tabindex="0"><code>package main
import &#34;fmt&#34;

func main() {
	seasons := []string{&#34;Spring&#34;, &#34;Summer&#34;, &#34;Autumn&#34;, &#34;Winter&#34;}
	for ix, season := range seasons {
		fmt.Printf(&#34;Season %d is: %s\n&#34;, ix, season)
	}

	var season string
	for _, season = range seasons {
		fmt.Printf(&#34;%s\n&#34;, season)
	}
}
</code></pre><p>slices_forrange2.go 给出了一个关于字符串的例子， <code>_</code> 可以用于忽略索引。</p>
<p>如果你只需要索引，你可以忽略第二个变量，例如：</p>
<pre tabindex="0"><code>for ix := range seasons {
	fmt.Printf(&#34;%d&#34;, ix)
}
// Output: 0 1 2 3
</code></pre><p>如果你需要修改 <code>seasons[ix]</code> 的值可以使用这个版本。</p>
<p><strong>多维切片下的 for-range：</strong></p>
<p>通过计算行数和矩阵值可以很方便的写出如（参考<a href="07.1.md">第 7.1.3 节</a>）的 <code>for</code> 循环来，例如（参考<a href="07.5.md">第 7.5 节</a>的例子 <a href="exercises/chapter_7/multidim_array.go">multidim_array.go</a>）：</p>
<pre tabindex="0"><code>for row := range screen {
	for column := range screen[row] {
		screen[row][column] = 1
	}
}
</code></pre><p><strong>问题 7.5</strong> 假设我们有如下数组：<code>items := [...]int{10, 20, 30, 40, 50}</code></p>
<p>a) 如果我们写了如下的 <code>for</code> 循环，那么执行完 <code>for</code> 循环后的 <code>items</code> 的值是多少？如果你不确定的话可以测试一下:)</p>
<pre tabindex="0"><code>for _, item := range items {
	item *= 2
}
</code></pre><p>b) 如果 a) 无法正常工作，写一个 <code>for</code> 循环让值可以变成自身的两倍。</p>
<p><strong>问题 7.6</strong> 通过使用省略号操作符 <code>...</code> 来实现累加方法。</p>
<p><strong>练习 7.7</strong> <a href="exercises/chapter_7/sum_array.go">sum_array.go</a></p>
<p>a) 写一个 <code>Sum()</code> 函数，传入参数为一个 <code>float32</code> 数组成的数组 <code>arrF</code>，返回该数组的所有数字和。</p>
<p>如果把数组修改为切片的话代码要做怎样的修改？如果用切片形式方法实现不同长度数组的的和呢？</p>
<p>b) 写一个 <code>SumAndAverage()</code> 方法，返回两个 int 和 <code>float32</code> 类型的未命名变量的和与平均值。</p>
<p><strong>练习 7.8</strong> <a href="exercises/chapter_7/min_max.go">min_max.go</a></p>
<p>写一个 <code>minSlice()</code> 方法，传入一个 <code>int</code> 的切片并且返回最小值，再写一个 <code>maxSlice()</code> 方法返回最大值。</p>

		</div>
	</div>
</div>


<div class="container">
    
    <div class="row">
        
        <div class="col-5">
            <a class="page-link link-dark text-end dh" href="/post/golang/2022.07.27-%E5%88%87%E7%89%87/">
                <h5>前一篇</h5><br>
                Go程序的切片
            </a>            
        </div>
        
        <div class="col-2">
        </div>
        
        <div class="col-5">
            <a class="page-link link-dark text-start dh" href="/post/golang/2022.07.29-%E5%88%87%E7%89%87%E9%87%8D%E7%BB%84reslice/">
                <h5>后一篇</h5><br>
                Go程序的切片重组reslice
            </a>            
        </div>
        
    </div>
    
</div>

        </div><br><br>
<footer class="container">
    <h2>友情链接</h2>
    <hr>
    <nav class="nav nav-pills flex-column flex-sm-row">
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/gnzg/index.html" target="_blank">孤鸟之歌</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/mm/index.html" target="_blank">生成随机字符</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/md/index.html" target="_blank">MarkDown</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://gitee.com/" target="_blank">Gitee</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://github.com/" target="_blank">Github</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.aliyun.com/" target="_blank">阿里云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://cloud.tencent.com/" target="_blank">腾讯云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.oschina.net/" target="_blank">OSCHINA开源中国</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://gitee.com/wiseai/the-way-to-go_ZH_CN/blob/master/eBook/directory.md" target="_blank">the way to go</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://topgoer.com/" target="_blank">golang文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://goframe.org/display/gf" target="_blank">GoFrame</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.aliyundrive.com/" target="_blank">阿里云盘</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://cn.vuejs.org/" target="_blank">vue3文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://element-plus.gitee.io/zh-CN/" target="_blank">element-plus文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.runoob.com/vue3/vue3-tutorial.html" target="_blank">vue3菜鸟教程</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://v5.bootcss.com/" target="_blank">bootstrap v5 中文文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.bootstrap.cn/" target="_blank">bootstrap文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://caddy2.dengxiaolong.com/docs/" target="_blank">caddy中文教程</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.58pic.com/" target="_blank">千图</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://ifonts.com/" target="_blank">iFonts</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://marketing.qiniu.com/" target="_blank">七牛云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.ixigua.com/" target="_blank">西瓜视频</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/yugang/index.html" target="_blank">鱼缸计算</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://justcc.mengkang.net/#/" target="_blank">C语言JustCC</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/pptist/" target="_blank">PPTist</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="/index.xml" target="_blank">RSS</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.kancloud.cn/idcpj/python/418553" target="_blank">参考资料</a>
        
    </nav>

    <div class="copyright text-center">
      <span class="power-by">
        Powered by <a class="links" href="https://gohugo.io" target="_blank">Hugo</a>
    </span>
    <span>|</span>
    <span>
        Theme - <a class="links" href="https://github.com/wiseai-go/blog-hugo" target="_blank">WiseAI</a>
    </span>
    <br>
    <span class="copyright-year">
        &copy;
        
        2017 -
        2023<span>
            陇ICP备15000157号
            
        </span></span>

</div>
</footer>
<script src="/js/bootstrap.bundle.min.js"></script>


</body>
</html>
